<?php

/**
 * Order short summary.
 *
 * Order description.
 *
 * @version 1.0
 * @author GALAXY
 */
class Order extends Shop_Controller
{
    public function __construct()
    {
        parent::__construct();
        $this->load->Model('Goods_order_model');
        $this->load->Model('Goods_cart_model');
        $this->load->Model('Customer_region_model');
        $this->load->Model('Goods_inventory_model');
    }

    private function get_order_sn()
    {
        /* 选择一个随机的方案 */
        mt_srand((double) microtime() * 1000000);
        return date('Ymd') . str_pad(mt_rand(1, 99999), 5, '0', STR_PAD_LEFT);
    }
    public function to_order()
    {
        $bacrurl='http://'.$_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI'];
        $this->check_redirect($bacrurl);

        $cart_id=$this->uri->segment(3);
        $customer_id=$this->get_customer_id();
        $order_model=$this->Goods_order_model->get_order_by_customer_cart($customer_id,$cart_id);
        //p($order_model);
        if(empty($order_model))
        {

            $cartModel=$this->Goods_cart_model->get_cart_by_id($cart_id);

            $orderModel=$this->Goods_order_model;
            $orderModel->goods_id=$cartModel->goods_id;
            $orderModel->count=$cartModel->count;
            $orderModel->color_id=$cartModel->color_id;
            $orderModel->size_id=$cartModel->size_id;
            $orderModel->customer_id=$cartModel->customer_id;
            $orderModel->order_code=$this->get_order_sn();
            $orderModel->addtime=date('Y-m-d H:i');
            $orderModel->order_msg='';
            $orderModel->order_state=0;
            $orderModel->deliver_goods_state=0;
            $orderModel->ali_code='';
            $orderModel->from_cart_id=$cart_id;
            $region_defaultmodel=$this->Customer_region_model->get_default_by_customer($customer_id);
            $orderModel->customer_region_id=!empty($region_defaultmodel)?$region_defaultmodel->customer_region_id:0;
            $data['orderModel']= $this->Goods_order_model->add_order($orderModel);
            if(!empty($data['orderModel']))
            {
                $this->Goods_cart_model->del_cart($cart_id);
                $data['goods_cart_html']=$this->get_cart_count();//更新购物车数量-Controller控制器有定义获取
            }
        }else{
            $data['orderModel']=$order_model;

        }
        $data['customer_id']=$customer_id;
        $data['customer_add_list']=$this->Customer_region_model->get_customer_region_by_customer_id($customer_id);
        //p($data['customer_add_list']);
        $this->load->view('Pre/order/to_order.html',$data);
    }

    public function order_pay()
    {
        $bacrurl='http://'.$_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI'];
        $this->check_redirect($bacrurl);
        $order_id=$this->uri->segment(3);
        $customer_id=$this->get_customer_id();;
        $order_model=$this->Goods_order_model->get_order_by_order_id($order_id);

        $data['orderModel']=$order_model;
        $data['customer_id']=$customer_id;
        $data['customer_add_list']=$this->Customer_region_model->get_customer_region_by_customer_id($customer_id);
        $this->load->view('Pre/order/to_order.html',$data);

    }

    public function goods_pay()
    {
        $bacrurl=$this->input->get('backurl');
        $this->check_redirect($bacrurl);
        $customer_id=$this->get_customer_id();
        $orderModel=$this->Goods_order_model;
        $orderModel->goods_id=$this->input->get('goodsid');
        $orderModel->count=$this->input->get('goods_count');
        $orderModel->color_id=$this->input->get('colorid');
        $orderModel->size_id=$this->input->get('sizeid');
        $orderModel->customer_id=$customer_id;
        $orderModel->order_code=$this->get_order_sn();
        $orderModel->addtime=date('Y-m-d H:i');
        $orderModel->order_msg='';
        $orderModel->order_state=0;
        $orderModel->deliver_goods_state=0;
        $orderModel->ali_code='';
        $orderModel->from_cart_id=0;
        $region_defaultmodel=$this->Customer_region_model->get_default_by_customer($customer_id);
        $orderModel->customer_region_id=!empty($region_defaultmodel)?$region_defaultmodel->customer_region_id:0;
        $exis_order_model=$this->Goods_order_model->get_exis_order($orderModel);//判断此商品是否存在
        if(empty($exis_order_model))//如存在
        {
            $data['orderModel']=$this->Goods_order_model->add_order($orderModel);
        }else
        {
            $data['orderModel']=$exis_order_model;
        }

        $data['customer_id']=$customer_id;
        $data['customer_add_list']=$this->Customer_region_model->get_customer_region_by_customer_id($customer_id);
        $this->load->view('Pre/order/to_order.html',$data);
        //echo $bacrurl;
    }

    public function update_order_count()
    {
        $this->load->library('ajaxMsgModel');
        if($this->check())
        {

            $orderid=$this->input->post('orderid');
            $new_val=$this->input->post('new_val');
            $goodorder_model=$this->Goods_order_model->get_order_by_id($orderid);
            $inventory_count=$this->Goods_inventory_model->get_goods_inventory_count($goodorder_model);
            if($inventory_count->inventory_count<$new_val)
            {
                $this->ajaxmsgmodel->Msg='库存没有这么多商品，请减少该商品的数量';
                $this->ajaxmsgmodel->Statu='err';
            }
            else
            {
                $res=$this->Goods_order_model->update_order_count($orderid,$new_val);
                if($res)
                {

                    $this->ajaxmsgmodel->Msg='更新订单成功';
                    $this->ajaxmsgmodel->Statu='ok';
                }
                else
                {
                    $this->ajaxmsgmodel->Msg='更新订单失败';
                    $this->ajaxmsgmodel->Statu='err';
                }
            }
        } else{
            $this->ajaxmsgmodel->Statu='okto';
            $this->ajaxmsgmodel->BackUrl=site_url('customer/r_login').'?backurl='.$this->input->post('backurl');
        }
        echo(json_encode($this->ajaxmsgmodel));
    }

    public function set_mail_add()
    {
        $this->load->library('ajaxMsgModel');
        if($this->check())
        {
            $orderid=$this->input->post('orderid');
            $region_id=$this->input->post('region_id');
            $res=$this->Goods_order_model->set_mail_add($orderid,$region_id);
            if($res)
            {

                $this->ajaxmsgmodel->Msg='更新订单成功';
                $this->ajaxmsgmodel->Statu='ok';
                $this->ajaxmsgmodel->BackUrl=$this->input->post('backurl');
                $this->ajaxmsgmodel->Data=$this->Goods_order_model->get_mail_add($region_id);
            }
            else
            {
                $this->ajaxmsgmodel->Msg='更新订单失败';
                $this->ajaxmsgmodel->Statu='err';
            }
        } else{
            $this->ajaxmsgmodel->Statu='okto';
            $this->ajaxmsgmodel->BackUrl=site_url('customer/r_login').'?backurl='.$this->input->post('backurl');
        }
        echo(json_encode($this->ajaxmsgmodel));
    }

    //删除订单
    public function del_order()
    {
        $this->load->library('ajaxMsgModel');
        if($this->check())
        {
            $orderid=$this->input->post('order_id');
            $customer_page_url=$this->input->post('customer_page_url');
            $backurl=$this->input->post('backurl');
            $res=$this->Goods_order_model->del_order($orderid);
            if($res)
            {

                $this->ajaxmsgmodel->Msg='删除订单成功';
                $this->ajaxmsgmodel->Statu='ok';
                $this->ajaxmsgmodel->BackUrl=!empty($customer_page_url)?$customer_page_url: $backurl;
            }
            else
            {
                $this->ajaxmsgmodel->Msg='删除订单失败';
                $this->ajaxmsgmodel->Statu='err';
            }
        } else{
            $this->ajaxmsgmodel->Statu='okto';
            $this->ajaxmsgmodel->BackUrl=site_url('customer/r_login').'?backurl='.$this->input->post('backurl');
        }
        echo(json_encode($this->ajaxmsgmodel));
    }

    public function order_to_pay()
    {
        $url=$this->input->post('backurl');
        $this->check_redirect($url);
        $res=$this->Goods_order_model->update_order_msg($this->input->post("goods_order_id"),$this->input->post('order_msg'));
        if($res)
        {
            $config= $this->set_get_config();
            $this->load->library('alipay/lib/alipay_submit',$config);
            $this->load->library('alipay/lib/alipay_core_function.php');
            $this->load->library('alipay/lib/alipay_md5_function.php');
            $goods_order_id=$this->input->post("goods_order_id");
            $orderModel=$this->Goods_order_model->get_to_pay_roder($goods_order_id);

            $out_trade_no =$orderModel->order_code;

            //订单名称，必填
            $subject = $orderModel->goodstitle;

            //付款金额，必填
            $total_fee = $orderModel->count*$orderModel->shop_price;

            //商品描述，可空
            $body ="购买商品：". $orderModel->goodstitle;





            /************************************************************/

            //构造要请求的参数数组，无需改动
            $parameter = array(
                    "service"       => $this->config->item('service','alipay'),
                    "partner"       => $this->config->item('partner','alipay'),//$alipay_config['partner'],
                    "seller_id"  => $this->config->item('seller_id','alipay'),//$alipay_config['seller_id'],
                    "payment_type"	=> $this->config->item('payment_type','alipay'),//$alipay_config['payment_type'],
                    "notify_url"	=> $this->config->item('notify_url','alipay'),//$alipay_config['notify_url'],
                    "return_url"	=> $this->config->item('return_url','alipay'),//$alipay_config['return_url'],

                    "anti_phishing_key"=>$this->config->item('anti_phishing_key','alipay'),//$alipay_config['anti_phishing_key'],
                    "exter_invoke_ip"=>$this->config->item('exter_invoke_ip','alipay'),//$alipay_config['exter_invoke_ip'],
                    "out_trade_no"	=> $out_trade_no,
                    "subject"	=> $subject,
                    "total_fee"	=> $total_fee,
                    "body"	=> $body,
                    "_input_charset"	=> trim(strtolower($this->config->item('input_charset','alipay')))//trim(strtolower($alipay_config['input_charset']))
                    //其他业务参数根据在线开发文档，添加参数.文档地址:https://doc.open.alipay.com/doc2/detail.htm?spm=a219a.7629140.0.0.kiX33I&treeId=62&articleId=103740&docType=1
                    //如"参数名"=>"参数值"

            );
            //建立请求
            $alipaySubmit = new alipay_submit($config);
            $html_text = $alipaySubmit->buildRequestForm($parameter,"get", "确认");
            echo $html_text;
        }
        else{

            _Msg_Redirect($url, '订单留言信息未失败，支付终止');
        }

    }


    public function respond()
    {

        //$this->config->load('alipay',TRUE);
        //$this->config->set_item('partner','2088521344460948','alipay');
        //$this->config->set_item('seller_id','2088521344460948','alipay');
        //$this->config->set_item('notify_url',site_url('order/respond'),'alipay');
        //$this->config->set_item('return_url',site_url('order/success'),'alipay');
        //$this->config->set_item('key','f9ervk5j2eohgxurcj2dw2q28xxjcnmw','alipay');
        //$config= $this->config->item('alipay');
        $config= $this->set_get_config();
        $this->load->library('alipay/lib/alipay_notify',$config);


        $alipayNotify = new alipay_notify($config);
        $verify_result = $alipayNotify->verifyNotify();
        if($verify_result) {//验证成功
            /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
            //请在这里加上商户的业务逻辑程序代


            //——请根据您的业务逻辑来编写程序（以下代码仅作参考）——

            //获取支付宝的通知返回参数，可参考技术文档中服务器异步通知参数列表

            //商户订单号

            $out_trade_no =$this->input->post('out_trade_no');// $_GET['out_trade_no'];

            //支付宝交易号

            $trade_no =$this->input->post('trade_no');// $_GET['trade_no'];

            //交易状态
            $trade_status =$this->input->post('trade_status');// $_GET['trade_status'];


            if($this->input->post('trade_status') == 'TRADE_FINISHED') {
                //判断该笔订单是否在商户网站中已经做过处理
                //如果没有做过处理，根据订单号（out_trade_no）在商户网站的订单系统中查到该笔订单的详细，并执行商户的业务程序
                //请务必判断请求时的total_fee、seller_id与通知时获取的total_fee、seller_id为一致的
                //如果有做过处理，不执行商户的业务程序

                //注意：
                //退款日期超过可退款期限后（如三个月可退款），支付宝系统发送该交易状态通知

                //调试用，写文本函数记录程序运行情况是否正常
                //logResult("这里写入想要调试的代码变量值，或其他运行的结果记录");
                $order_code=$out_trade_no;
                $res= $this->Goods_order_model->update_order_state_goods_inventory($order_code,$trade_no);
                if(!$res)
                {
                    log_message('error','订单号：'.$order_code.'交易失败');
                }
            }
            else if ($this->input->post('trade_status') == 'TRADE_SUCCESS') {
                //判断该笔订单是否在商户网站中已经做过处理
                //如果没有做过处理，根据订单号（out_trade_no）在商户网站的订单系统中查到该笔订单的详细，并执行商户的业务程序
                //请务必判断请求时的total_fee、seller_id与通知时获取的total_fee、seller_id为一致的
                //如果有做过处理，不执行商户的业务程序

                //注意：
                //付款完成后，支付宝系统发送该交易状态通知

                //调试用，写文本函数记录程序运行情况是否正常
                //logResult("这里写入想要调试的代码变量值，或其他运行的结果记录");

                $order_code=$out_trade_no;
                $res= $this->Goods_order_model->update_order_state_goods_inventory($order_code,$trade_no);
                if(!$res)
                {
                    log_message('error','订单号：'.$order_code.'交易失败');
                }

            }

            //——请根据您的业务逻辑来编写程序（以上代码仅作参考）——

            echo "success";		//请不要修改或删除

            /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
        }
        else {
            log_message('error','验证失败');
            //验证失败
            echo "fail";

            //调试用，写文本函数记录程序运行情况是否正常
            //logResult("这里写入想要调试的代码变量值，或其他运行的结果记录");
        }
    }

    private function set_get_config()
    {
        $this->config->load('alipay',TRUE);
        $this->config->set_item('partner','2088521344460948','alipay');
        $this->config->set_item('seller_id','2088521344460948','alipay');
        $this->config->set_item('notify_url',site_url('order/respond'),'alipay');
        $this->config->set_item('return_url',site_url('order/success'),'alipay');
        $this->config->set_item('key','f9ervk5j2eohgxurcj2dw2q28xxjcnmw','alipay');
        $config= $this->config->item('alipay');
        return $config;
    }

    public function success()
    {

        $config= $this->set_get_config();
        $this->load->library('alipay/lib/alipay_notify',$config);
        $alipayNotify = new alipay_notify($config);
        $verify_result = $alipayNotify->verifyReturn();
        if($verify_result) {//验证成功
            /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
            //请在这里加上商户的业务逻辑程序代码

            //——请根据您的业务逻辑来编写程序（以下代码仅作参考）——
            //获取支付宝的通知返回参数，可参考技术文档中页面跳转同步通知参数列表

            //商户订单号

            $out_trade_no =$this->input->get('out_trade_no');// $_GET['out_trade_no'];

            //支付宝交易号

            $trade_no =$this->input->get('trade_no');// $_GET['trade_no'];

            //交易状态
            $trade_status =$this->input->get('trade_status');// $_GET['trade_status'];


            if($this->input->get('trade_status') == 'TRADE_FINISHED' || $this->input->get('trade_status') == 'TRADE_SUCCESS') {
                //判断该笔订单是否在商户网站中已经做过处理
                //如果没有做过处理，根据订单号（out_trade_no）在商户网站的订单系统中查到该笔订单的详细，并执行商户的业务程序
                //如果有做过处理，不执行商户的业务程序
                $data['msg']='支付成功';
                $this->load->view('Pre/order/pcmsg.html',$data);
            }
            else {
                $data['msg']='支付失败';
                $this->load->view('Pre/order/pemsg.html',$data);
            }

            //echo "验证成功<br />";

            //——请根据您的业务逻辑来编写程序（以上代码仅作参考）——

            /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
        }
        else {
            //验证失败
            //如要调试，请看alipay_notify.php页面的verifyReturn函数
            $data['msg']='该订单支付验证错误';
            $this->load->view('Pre/order/pemsg.html',$data);
        }
    }
}